package cn.leedsoft.and.crimeintent.controller.nerd_launcher;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.text.Collator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

/**
 * Created by leeds on 2016/8/22 14:26.
 */
public class NerdLauncherFragment extends ListFragment {
    public static NerdLauncherFragment newInstance() {

        Bundle args = new Bundle();

        NerdLauncherFragment fragment = new NerdLauncherFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        final PackageManager pm = getActivity().getPackageManager();
        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        System.out.println(">>>>找到" + resolveInfos.size() + "个activities");

        Collections.sort(resolveInfos, new Comparator<ResolveInfo>() {
            @Override
            public int compare(ResolveInfo lhs, ResolveInfo rhs) {
                Collator ca = Collator.getInstance(Locale.CHINA);//中文拼音排序
                return ca.compare(lhs.loadLabel(pm).toString(), rhs.loadLabel(pm).toString());
            }
        });

        setListAdapter(new ArrayAdapter<ResolveInfo>(getActivity(), android.R.layout.simple_list_item_1, resolveInfos) {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                ResolveInfo ri = getItem(position);
                TextView tv = (TextView) view;
                tv.setText(ri.loadLabel(pm));
                return view;
            }
        });
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        ResolveInfo ri = (ResolveInfo) getListAdapter().getItem(position);
        ActivityInfo ai = ri.activityInfo;

        if (ai == null) return;

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_MAIN);
        intent.setClassName(ai.packageName, ai.name);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        System.out.println(String.format("MAIN/LAUNCHER隐式intent启动应用：packageName:%1$s, className:%2$s", ai.packageName, ai.name));
        startActivity(intent);
    }
}
